package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.core.RoleEnum;
import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.core.movieservice.param.NameParam;
import la.iok.hzsvn.lewin.movie.entity.MovieTag;
import la.iok.hzsvn.lewin.movie.mapper.MovieTagMapper;
import la.iok.hzsvn.lewin.mybatis.service.BaseServiceImpl;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.tools.exception.SystemException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class MovieTagServiceImpl extends BaseServiceImpl<MovieTag,MovieTagMapper,Long> implements MovieTagService{
    public MovieTagServiceImpl(MovieTagMapper movieTagMapper) {
        super(movieTagMapper);
    }

    @Override
    public Long save(@NotNull Token token, @NotNull NameParam param) {
        ErrorCode.NAME_BLANK_ERROR.assertNotBlank(param.getName());
        ErrorCode.ADMIN_DENIED.assertTrue(token.hasAuthority(RoleEnum.Admin));
        try{
            MovieTag movieTag = new MovieTag();
            movieTag.setName(param.getName());
            mapper.insertSelective(movieTag);
            return movieTag.getId();
        }catch (DuplicateKeyException e){
            throw new SystemException(String.format("已经存在标签[%s]",param.getName()),e);
        }
    }

    @Override
    public void delete(@NotNull Token token, @Nullable Long id) {
        if(id == null){
            return;
        }
        ErrorCode.ADMIN_DENIED.assertTrue(token.hasAuthority(RoleEnum.Admin));
        delete(id);
    }

    @Override
    public void update(@NotNull Token token,@Nullable Long id, @NotNull NameParam param) {
        if(id == null){
            return;
        }
        try{
            ErrorCode.NAME_BLANK_ERROR.assertNotBlank(param.getName());
            ErrorCode.ADMIN_DENIED.assertTrue(token.hasAuthority(RoleEnum.Admin));
            MovieTag entity = mapper.selectById(id);
            ErrorCode.RECORD_NOT_EXIST.assertNotNull(entity,id);
            mapper.updateProperty(id,"name",param.getName());
        }catch (DuplicateKeyException e){
            throw new SystemException(String.format("已经存在标签[%s]",param.getName()),e);
        }
    }
}
